﻿-- Дефрагментизация базы данных
CREATE PROCEDURE [dbo].[USPTOOLS_DBDefragDatabase]
	@dbname [nvarchar](256) = null
WITH EXECUTE AS CALLER
AS
BEGIN 
SET @dbname = isnull(@dbname,db_name())
DECLARE @quoteddbname nvarchar(256)
set @quoteddbname = quotename( @dbname )
EXEC('
USE '+ @quoteddbname +'
DECLARE @sTableName sysname
DECLARE PKMS_Tables CURSOR LOCAL FOR 
select table_name from information_schema.tables 
where table_type = ''base table'' order by 1 
OPEN PKMS_Tables 
FETCH NEXT FROM PKMS_Tables INTO @sTableName 

WHILE @@FETCH_STATUS = 0 
BEGIN 
select @sTablename = quotename(@sTablename, ''[]'')
EXEC('' DBCC DBREINDEX ( ''+@sTableName+'') WITH NO_INFOMSGS'')
FETCH NEXT FROM PKMS_Tables INTO @sTableName 
END 
CLOSE PKMS_Tables')
END


